package com.spice.im.utils;

//import com.stb.appearancetime.R;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.GalleryImageLoader;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.FileUtils;
import cn.finalteam.toolsfinal.Logger;



//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.spice.im.ContactFrameActivity;
import com.spice.im.R;
import com.spice.im.SpiceApplication;
import com.spice.im.attendance.AttendanceClassSection;
import com.spice.im.ui.HandyTextView;
import com.stb.isharemessage.service.XmppConnectionAdapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
//import cn.com.ctbri.pp2transitcard.tools.ConstValuesLib;
//import cn.com.ctbri.pp2transitcard.tools.R;

public class MyDialogPopWinGroup extends Dialog implements
		android.view.View.OnClickListener, ConstValuesLib {
	public static final int ButtonCancle = 0;// 显示取消按钮
	public static final int ButtonConfirm = 1;// 显示确定按钮
	public static final int ButtonBoth = 2;// 显示全部按钮
	public static final int ButtonNone = 3;// 不显示任何的按钮
	View view = null;
	Button btn_confirm;
	Button btn_cancel;
	int buttonNums = 2;
	//TextView theView;
	TextView tx_title;
	Activity activity;
	boolean visiable = true;
	MyDialogListener listener;
	CharSequence g_Msg = "";
	String title = "";
	String posiBtnMsg = "";
	String negaBtnMsg = "";
	ViewGroup container;
	// 提示信息
	private String msg = null;
//	private TextView theView;//原textview  ---占位符号 显示拍照时，该textview不显示gone
//	private TextView textViewDialog2;//占位符号 显示拍照时，该textview不显示gone
	
	
    /** TextView选择框 */
//    private TextView mSelectTv;
	private EditText mGroupName;
    
    private LinearLayout kaoqin_linearlayout_photo;//
	private ImageView mIvUserPhoto;
	private LinearLayout mLayoutSelectPicture;
	private LinearLayout mLayoutTakePicture;
	private Bitmap mUserPhoto;
	private final OkListener mOkListener = new OkListener();
	private String CurrentUid;
	private String procinsid;
	private String groupName;
	private String tagimg;
	
	public void setUserPhoto(Bitmap bitmap) {
		if (bitmap != null) {
			mUserPhoto = bitmap;
			mIvUserPhoto.setImageBitmap(mUserPhoto);
			return;
		}
		showCustomToast("未获取到图片");
		mUserPhoto = null;
		mIvUserPhoto.setImageResource(R.drawable.ic_common_def_header);
	}
    
    /**
     * Listener.
     */
    private class OkListener implements View.OnClickListener {
	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.reg_photo_layout_selectphoto:
					GalleryHelper.openGallerySingle(activity, true, new GalleryImageLoader());
					break;
	
				case R.id.reg_photo_layout_takepicture:
					takePhotoAction();
				break;
			}
	
		}
    };
	
    
    public Object getSelectValue(){
    	return mGroupName.getText().toString();
//    	if(selectValues.get(mSelectTv.getText().toString())!=null){
//    		if(selectValues.get(mSelectTv.getText().toString()) instanceof AttendanceClassSection)
//    			return (AttendanceClassSection)(selectValues.get(mSelectTv.getText().toString()));
//    		else
//    			return (String)(selectValues.get(mSelectTv.getText().toString()));
//    	}else
//    		return null;
    }
    public String getGroupName(){
    	return mGroupName.getText().toString();
    }
    
    public String getPhotoName(){
    	if(transformfilepath!=null
    			&& transformfilepath.length()!=0
    			&& !transformfilepath.equalsIgnoreCase("null")){
    		if(transformfilepath.startsWith("http://")){
    			return transformfilepath;
    		}else{
	    		int idx = transformfilepath.lastIndexOf("/");
	    		if(idx!=-1){
	    			return transformfilepath.substring(idx+1);
	    		}else
	    			return transformfilepath;
    		}
    	}else if(tagimg!=null && tagimg.length()!=0 && !tagimg.equalsIgnoreCase("null")){//不做任何修改直接返回
    		if(tagimg.lastIndexOf("/")!=-1)
    			return tagimg.substring(tagimg.lastIndexOf("/")+1);
    		else
    			return tagimg;
    	}
    	else 
    		return null;
    }

//    /** popup窗口里的ListView */
//    private ListView mTypeLv;
//
//    /** popup窗口 */
//    private PopupWindow typeSelectPopup;
//
//    /** 模拟的假数据 */
//    private List<String> testData;
//
//    /** 数据适配器 */
//    private ArrayAdapter<String> testDataAdapter;
//    
//    private ArrayList aClassSections;
//    
//    private HashMap selectValues = new HashMap();
    
    
	private View lineSeperator;

	MyDialogContentClickListener contentListener;

	public MyDialogPopWinGroup(Activity activity) {
		super(activity);
		this.activity = activity;
	}

	public MyDialogPopWinGroup(Activity activity, int theme, MyDialogListener listener,
			int btnNums, String CurrentUid,String procinsid,String groupName,String tagimg) {
		super(activity, theme);
		this.activity = activity;
		this.listener = listener;
		buttonNums = btnNums;
//		this.aClassSections = aClassSections;
		this.CurrentUid = CurrentUid;
		this.procinsid = procinsid;
		this.groupName = groupName;
		this.tagimg = tagimg;
	}

	public MyDialogPopWinGroup(Activity activity, int theme, MyDialogListener listener,
			int btnNums, String msg) {
		super(activity, theme);
		this.activity = activity;
		this.listener = listener;
		buttonNums = btnNums;
		this.msg = msg;
		this.g_Msg = msg;
	}

	public void setContentListener(MyDialogContentClickListener contentListener) {
		this.contentListener = contentListener;
	}

	public void setTitleTxt(String msg) {
		title = msg;
	}

	public void MyDialogSetMsg(CharSequence msg) {
		g_Msg = msg;
	}

	public void setPosiBtnMsg(String posiMsg) {
		posiBtnMsg = posiMsg;
	}

	public void setNegaBtnMsg(String negaMsg) {
		negaBtnMsg = negaMsg;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mydialog_group);
		btn_confirm = (Button) findViewById(R.id.btn_confirm);
		btn_confirm.setOnClickListener(this);
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(this);
		container = (ViewGroup) findViewById(R.id.rl_container);
		lineSeperator = findViewById(R.id.dialog_btn_line_seperator);
		if (buttonNums == ButtonConfirm) {
			btn_cancel.setVisibility(View.GONE);
			lineSeperator.setVisibility(View.GONE);
			btn_confirm.setText(R.string.i_kuown);
			btn_confirm
					.setBackgroundResource(R.drawable.common_res_alertdialog_full_btn_selector);
		} else if (buttonNums == ButtonCancle) {
			btn_confirm.setVisibility(View.GONE);
			lineSeperator.setVisibility(View.GONE);
			btn_cancel
					.setBackgroundResource(R.drawable.common_res_alertdialog_full_btn_selector);
		} else if (buttonNums == ButtonNone) {
			btn_confirm.setVisibility(View.GONE);
			btn_cancel
					.setBackgroundResource(R.drawable.common_res_base_alertdialog_full_btn_bg_norrmal);
		}
		if (view != null) {
			container.removeAllViews();
			android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.FILL_PARENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			container.addView(view, params);
		}
//		theView = (TextView) findViewById(R.id.textViewDialog);
//		textViewDialog2 = (TextView) findViewById(R.id.textViewDialog2);
		mGroupName = (EditText) findViewById(R.id.group_et_name);
		
//		mGroupName.setOnClickListener(this);
		tx_title = (TextView) findViewById(R.id.txt_str_prompt);
		
	
		
		
		kaoqin_linearlayout_photo = (LinearLayout) findViewById(R.id.kaoqin_linearlayout_photo);
        mIvUserPhoto = (ImageView) findViewById(R.id.reg_photo_iv_userphoto);
		mLayoutTakePicture = (LinearLayout) findViewById(R.id.reg_photo_layout_takepicture);
		mLayoutTakePicture.setOnClickListener(mOkListener);
		
		mLayoutSelectPicture = (LinearLayout) findViewById(R.id.reg_photo_layout_selectphoto);
		mLayoutSelectPicture.setOnClickListener(mOkListener);

		// 如果提示信息不为null则显示
//		if (g_Msg != null && !"".equals(g_Msg)) {
//			theView.setText(g_Msg);
//			if (g_Msg.toString().contains("常见问题")) {
//				theView.setOnClickListener(new View.OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						Intent intent = new Intent(activity, HelpActivity.class);
//						activity.startActivity(intent);
//						MyDialog.this.dismiss();
//					}
//				});
//			}
//		}
//		if (g_Msg != null && !"".equals(g_Msg)) {
		if (g_Msg != null) {
//			theView.setText(g_Msg);
//			theView.setOnClickListener(this);
		}
	}

	@Override
	protected void onStart() {
//		if (!visiable) {
//			theView.setVisibility(View.GONE);
//		}
//		if (g_Msg != null && !g_Msg.equals("")) {
//			theView.setText(g_Msg);
//		}
		if (groupName != null && !groupName.equals(""))
			mGroupName.setText(groupName);
		if (title != null && !title.equals("")) {
			tx_title.setText(title);
		}
		if (!posiBtnMsg.equals("")) {
			btn_confirm.setText(posiBtnMsg);
		}
		if (!negaBtnMsg.equals("")) {
			btn_cancel.setText(negaBtnMsg);
		}
		if(tagimg!=null && tagimg.length()!=0 && !tagimg.equalsIgnoreCase("null"))
			ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+tagimg, mIvUserPhoto,SpiceApplication.getInstance().options);
		super.onStart();
	}

	@Override
	public void onClick(View v) {
		if (listener != null || contentListener != null) {
			if (v.getId() == R.id.btn_confirm) {
				if(listener != null)
				listener.onPositiveClick(this, v);
			} else if (v.getId() == R.id.btn_cancel) {
				if(listener != null)
				listener.onNegativeClick(this, v);
			} else if (v.getId() == R.id.textViewDialog) {
				if(contentListener != null)
				contentListener.onClickContent(this, v, g_Msg);
			}
		}
//		if(v.getId() == R.id.tv_select_input){//下拉选择框
//            // 点击控件后显示popup窗口
//            initSelectPopup();
//            // 使用isShowing()检查popup窗口是否在显示状态
//            if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
//                typeSelectPopup.showAsDropDown(mSelectTv, 0, 10);
//            }
//		}
		else if (isShowing()) {
			dismiss();
		}
	}

	public void setMsgViewVisiable(boolean visiable) {
		this.visiable = visiable;
	}

	public interface MyDialogListener {
		public void onPositiveClick(Dialog dialog, View view);

		public void onNegativeClick(Dialog dialog, View view);
	}

	public interface MyDialogContentClickListener {
		public void onClickContent(Dialog dialog, View view,
				CharSequence content);
	}

	@Override
	public void show() {
		if (activity != null && !activity.isFinishing()) {
			super.show();
		}
	}

	public void setView(View view) {
		this.view = view;
	}
	
	
//    /**
//     * 初始化popup窗口
//     */
//    private void initSelectPopup() {
//    	//android:divider="@drawable/divider"
////        android:fastScrollEnabled="false"
////        android:footerDividersEnabled="false"
////        android:headerDividersEnabled="false"
////        android:smoothScrollbar="true"
////        ptr:ptrAnimationStyle="flip"
////        android:cacheColorHint="@color/transparent"
////        android:background="@color/background_main" 
////        android:listSelector="@drawable/list_selector_transition"
//        mTypeLv = new ListView(this.activity);
////        Drawable drawable2 = ContextCompat.getDrawable(this.activity, R.drawable.bg_card);
////        mTypeLv.setBackgroundDrawable(drawable2);
//        mTypeLv.setDivider(ContextCompat.getDrawable(this.activity, R.drawable.divider));
//        mTypeLv.setBackgroundColor(this.activity.getResources().getColor(R.color.background_main));
//        mTypeLv.setCacheColorHint(this.activity.getResources().getColor(R.color.transparent));
//        mTypeLv.setSelector(R.drawable.list_selector_transition);
//        TestData(aClassSections);
//        // 设置适配器
//        testDataAdapter = new ArrayAdapter<String>(this.activity, R.layout.popup_text_item, testData);
//        mTypeLv.setAdapter(testDataAdapter);
//
//        // 设置ListView点击事件监听
//        mTypeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            	setUploadStatus(false);
//                // 在这里获取item数据
//                String value = testData.get(position);
//                // 把选择的数据展示对应的TextView上
//                mSelectTv.setText(value);
//                if(value.indexOf("自由签")!=-1){//如果是自由签，自必须拍照上传照片
//                	theView.setVisibility(View.GONE);//原textview  ---占位符号 显示拍照时，该textview不显示gone
//                	textViewDialog2.setVisibility(View.GONE);//占位符号 显示拍照时，该textview不显示gone
//                	kaoqin_linearlayout_photo.setVisibility(View.VISIBLE);
//                }else{
//                	kaoqin_linearlayout_photo.setVisibility(View.GONE);
//                	theView.setVisibility(View.VISIBLE);//原textview  ---占位符号 显示拍照时，该textview不显示gone
//                	textViewDialog2.setVisibility(View.VISIBLE);//占位符号 显示拍照时，该textview不显示gone
//                }
//                // 选择完后关闭popup窗口
//                typeSelectPopup.dismiss();
//            }
//        });
//        typeSelectPopup = new PopupWindow(mTypeLv, mSelectTv.getWidth(), LayoutParams.WRAP_CONTENT, true);
//        // 取得popup窗口的背景图片
//        Drawable drawable = ContextCompat.getDrawable(this.activity, R.drawable.bg_corner);
//        typeSelectPopup.setBackgroundDrawable(drawable);
//        typeSelectPopup.setFocusable(true);
//        typeSelectPopup.setOutsideTouchable(true);
//        typeSelectPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                // 关闭popup窗口
//                typeSelectPopup.dismiss();
//            }
//        });
//    }
//
//    /**
//     * 模拟假数据
//     */
//    private void TestData(ArrayList aClassSections) {
//        testData = new ArrayList();
////        for (int i = 0; i < 10; i++) {
////            String str = new String("数据" + i);
////            testData.add(str);
////        }
//        
//        //testData.add(1+"-"+"自由签");
//        //selectValues.put(1+"-"+"自由签", "00000000000000000000000000000000");
//        if(aClassSections!=null && aClassSections.size()!=0){
//        	for(int i=0;i<aClassSections.size();i++){//i+2
//        		testData.add((i+1)+"-"+((AttendanceClassSection)aClassSections.get(i)).getOnoffdutyname());
//        		selectValues.put((i+1)+"-"+((AttendanceClassSection)aClassSections.get(i)).getOnoffdutyname(), (AttendanceClassSection)aClassSections.get(i));
//        	}
//        }else{
////        	testData.add("您所在的企业未设置考勤规则，请联系管理员.");
//        	testData.add(1+"-"+"自由签");
//            selectValues.put(1+"-"+"自由签", "00000000000000000000000000000000");
//        }
//    }
    
    
    
    //拍照start
    Uri uri = null;
	//利用requestCode区别开不同的返回结果
	//resultCode参数对应于子模块中setResut(int resultCode, Intent intent)函数中的resultCode值，用于区别不同的返回结果（如请求正常、请求异常等）
	//对应流程：
	//母模块startActivityForResult--触发子模块，根据不同执行结果设定resucode值，最后执行setResut并返回到木模块--母模块触发onActivityResult，根据requestcode参数区分不同子模块。
    //@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==2 && resultCode==2 && data!=null){
        	String filepath = data.getStringExtra("filepath");
        	Toast.makeText(this.activity, "filepath="+filepath, Toast.LENGTH_LONG).show();
			if(filepath.length() > 0){
//				sendFile(filepath);//P2P send file
				File file = new File(filepath);
				if (file.exists() && file.canRead()) {
					sendOfflineFile(filepath,"file");//send offline file via agent file server 
								    
				} else {
					Toast.makeText(this.activity, "file not exists", Toast.LENGTH_LONG).show();
				}
			}
        }
        else if ( requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

                if ( photoInfo != null ) {
//                    ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                    uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                    Toast.makeText(this.activity, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                    sendOfflineFile(photoInfo.getPhotoPath(),"img");
                }

                if ( photoInfoList != null ) {
                    Toast.makeText(this.activity, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
                }
            }
        }
        else if ( requestCode == GalleryHelper.TAKE_REQUEST_CODE ) {
            if (resultCode == android.app.Activity.RESULT_OK && mTakePhotoUri != null) {
                final String path = mTakePhotoUri.getPath();
                final PhotoInfo info = new PhotoInfo();
                info.setPhotoPath(path);
//                updateGallery(path);

                final int degress = BitmapUtils.getDegress(path);
                if (degress != 0) {
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            toast("请稍等…");
                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Bitmap bitmap = rotateBitmap(path, degress);
                                saveRotateBitmap(bitmap, path);
                                bitmap.recycle();
                            } catch (Exception e) {
                                Logger.e(e);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void voids) {
                            super.onPostExecute(voids);
//                            takeResult(info);
                            toPhotoCrop(info);
                        }
                    }.execute();
                } else {
//                    takeResult(info);
                	toPhotoCrop(info);
                }
            } else {
                toast("拍照失败");
            }
        } else if ( requestCode == GalleryHelper.CROP_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.CROP_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                resultSingle(photoInfo);
            }
        } else if ( requestCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
            PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
            List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

            if ( photoInfo != null ) {
//                ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                Toast.makeText(this.activity, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                sendOfflineFile(photoInfo.getPhotoPath(),"img");
            }

            if ( photoInfoList != null ) {
                Toast.makeText(this.activity, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    //recodeTime
    String transformfilepath = "";
    String transformfiletype = "";
    private void sendOfflineFile(String filepath,String type) {
		
    	transformfilepath = filepath;
    	transformfiletype = type;
    	
		try{
    		File file2 = new File(transformfilepath);
    		if(file2.exists()){
    			Bitmap bitmap = BitmapFactory.decodeFile(transformfilepath);
    			setUserPhoto(bitmap);
    			upload(transformfilepath,"9999");
    			
    		}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    
    /**
     * 拍照
     */
    String mPhotoTargetFolder = null;
    Uri mTakePhotoUri = null;
    protected void takePhotoAction() {

        if (!DeviceUtils.existSDCard()) {
//            toast("没有SD卡不能拍照呢~");
        	Toast.makeText(this.activity, "没有SD卡不能拍照呢~", Toast.LENGTH_SHORT).show();
            return;
        }

        File takePhotoFolder = null;
        if (cn.finalteam.toolsfinal.StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            this.activity.startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
    }
    protected int mScreenWidth = 720;
    protected int mScreenHeight = 1280;
    protected Bitmap rotateBitmap(String path, int degress) {
        try {
            Bitmap bitmap = BitmapUtils.compressBitmap(path, mScreenWidth / 4, mScreenHeight / 4);
            bitmap = BitmapUtils.rotateBitmap(bitmap, degress);
            return bitmap;
        } catch (Exception e) {
            Logger.e(e);
        }

        return null;
    }

    protected void saveRotateBitmap(Bitmap bitmap, String path) {
        //保存
        BitmapUtils.saveBitmap(bitmap, new File(path));
        //修改数据库
        ContentValues cv = new ContentValues();
        cv.put("orientation", 0);
        ContentResolver cr = this.activity.getContentResolver();
        String where = new String(MediaStore.Images.Media.DATA + "='" + cn.finalteam.toolsfinal.StringUtils.sqliteEscape(path) +"'");
        cr.update(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv, where, null);
    }
    public void toast(String msg) {
        Toast.makeText(this.activity, msg, Toast.LENGTH_SHORT).show();
    }
    protected void resultSingle(PhotoInfo photoInfo) {
//        Intent intent = getIntent();
//        if (intent == null) {
//            intent = new Intent();
//        }
//        intent.putExtra(GalleryHelper.RESULT_DATA, photoInfo);
////        setResult(GalleryHelper.GALLERY_RESULT_SUCCESS, intent);
////        finish();
//        startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
    	
        if ( photoInfo != null ) {
//          ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
          uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
          Toast.makeText(this.activity, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
          sendOfflineFile(photoInfo.getPhotoPath(),"img");
      }
    }
    /**
     * 执行裁剪
     */
    protected void toPhotoCrop(PhotoInfo info) {
        Intent intent = new Intent(this.activity, PhotoCropActivity.class);
        intent.putExtra(PhotoCropActivity.PHOTO_INFO, info);
        this.activity.startActivityForResult(intent, GalleryHelper.CROP_REQUEST_CODE);
    }
    
    public void upload(String mPicPath,String fromAccount){
    	try{
            final File file = new File(mPicPath);  
            
            if (file != null) {  
//                String request = UploadUtil.uploadFile(file, requestURL);  
//                String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
            	String uploadHost = XmppConnectionAdapter.uploadHost.replace("OfflinefiletransferServlet", "UploadHeadServlet");
            	uploadHost = "http://10.0.2.2:8080/jeesite/maps/Resource/upload.jsp";
            	uploadHost = "http://59.52.226.115:8189/jeesite/maps/Resource/uploadFeed.jsp";
            	uploadHost = XmppConnectionAdapter.downloadPrefix+"/maps/Resource/uploadFeed.jsp";
//                RequestParams params=new RequestParams();  
////                params.addBodyParameter("msg",imgtxt.getText().toString());   
//                params.addBodyParameter(picPath.replace("/", ""), file);   
//                uploadMethod(params,uploadHost);
////                uploadImage.setText(request);  
                RequestParams params = new RequestParams();
//                params.addHeader("name", "value");
//                params.addHeader(HttpUtils.HEADER_ACCEPT_ENCODING, HttpUtils.ENCODING_GZIP);
                params.addHeader("Accept-Encoding", "gzip");
//                params.addQueryStringParameter("name", "value");
                params.addQueryStringParameter("fromAccount", CurrentUid);//代表存储目录  fromAccount
//                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.activity);
//        	    String uid = settings.getString("uidStr", "");
        	    params.addQueryStringParameter("uidStr", CurrentUid);
        	    Date dNow = new Date();   //当前时间
        	    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss"); //设置时间格式
		    	String defaultStartDate = sdf.format(dNow);    //格式化前3月的时间
//        	    params.addQueryStringParameter("saveName", defaultStartDate+".jpg");
		    	params.addQueryStringParameter("saveName", procinsid);
                params.addQueryStringParameter("sendType", "img");
                params.addQueryStringParameter("sendSize", "0");
                // 只包含字符串参数时默认使用BodyParamsEntity，
                // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//                params.addBodyParameter("fromAccount", fromAccount);
//                params.addBodyParameter("toAccount", toAccount);
//                params.addBodyParameter("sendType", "audio");
//                params.addBodyParameter("sendSize", (int) mRecord_Time+"");

                // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
                // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
                // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
                // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
                // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
//                BodyParamsEntity bpe = new BodyParamsEntity();
//                bpe.addParameter("fromAccount", fromAccount);
//                bpe.addParameter("toAccount", toAccount);
//                bpe.addParameter("sendType", "audio");
//                bpe.addParameter("sendSize", (int) mRecord_Time+"");
//                params.setBodyEntity(bpe);
                params.addBodyParameter("file", file);
                uploadMethod(params,uploadHost);
                
            }  
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
	private HttpUtils http;
	private HttpHandler handler;
	private boolean uploadStatus;//是否上传了工作照片
	public void setUploadStatus(boolean uploadStatus){
		this.uploadStatus = uploadStatus;
	}
	public boolean getUploadStatus(){
		return this.uploadStatus;
	}
    //上传照片start
    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
    	http = new HttpUtils();
    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	
    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
                    @Override  
                    public void onStart() {  
//                      msgTextview.setText("conn...");  
                    	setUploadStatus(false);
                    	mHandlerGroup.sendEmptyMessage(4);
                      
                    }  
                    @Override  
                    public void onLoading(long total, long current,boolean isUploading) {  
//                        if (isUploading) {  
//                          msgTextview.setText("upload: " + current + "/"+ total);  
//                        } else {  
//                          msgTextview.setText("reply: " + current + "/"+ total);  
//                        }  
    					android.os.Message message = mHandlerGroup.obtainMessage();
//    					message.arg1 = (int) (current*100/total);
    					message.arg1 = 80;//gzip 后 total为0
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandlerGroup.sendMessage(message);
                    }  
                    public void onSuccess(ResponseInfo<String> responseInfo) { 
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传成功"+responseInfo.statusCode+";reply: " + responseInfo.result);
                    	//statuscode == 200
//                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
                    	setUploadStatus(true);
                    	mHandlerGroup.sendEmptyMessage(2);
                    }  
                    public void onFailure(HttpException error, String msg) {  
//                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
                    	setUploadStatus(false);
                    	mHandlerGroup.sendEmptyMessage(3);
                    }  
                });  
        
    } 
    //上传照片end
    
    private  Dialog creatingProgress = null;
	private ProgressBar bar;
	private TextView progress;
	
	public void initialProgressDialog(){
		//创建处理进度条
		creatingProgress= new Dialog(this.activity,R.style.Dialog_loading_noDim);
		Window dialogWindow = creatingProgress.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		lp.width = (int) (this.activity.getResources().getDisplayMetrics().density*240);
		lp.height = (int) (this.activity.getResources().getDisplayMetrics().density*80);
		lp.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(lp);
		creatingProgress.setCanceledOnTouchOutside(false);//禁用取消按钮
		creatingProgress.setContentView(R.layout.activity_recorder_progress);
		
		progress = (TextView) creatingProgress.findViewById(R.id.recorder_progress_progresstext);
		bar = (ProgressBar) creatingProgress.findViewById(R.id.recorder_progress_progressbar);
	}
	Handler mHandlerGroup = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {

			case 1:
				
				progress.setText(msg.arg1+"%");//20150831 第三种方法
				bar.setProgress(msg.arg1);//20150831 第三种方法
				break;
			case 2:
				progress.setText("100%");//20150831 第三种方法
				bar.setProgress(100);//20150831 第三种方法
				
				creatingProgress.dismiss();
////				transformfilepath = 
//				if(transformfilepath.lastIndexOf("/")!=-1)
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath.substring(transformfilepath.lastIndexOf("/")+1);
//				else
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath;
				break;
			case 3:
				progress.setText("上传失败!");
				creatingProgress.dismiss();
				break;
			case 4:
				initialProgressDialog();
				creatingProgress.show();
				break;
			default:
				if(errorType!=5)
					showCustomToast(errorMsg[errorType]);
				break;
			}
		}

	};
	private String[] errorMsg = new String[]{"群聊创建成功.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"系统错误.群聊创建失败.",
			"用户已经加入了该群组，不能重复创建.",//0003
			"创建群组失败,hash校验失败"//0002
			};
	private int errorType = 5;
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(this.activity).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(this.activity);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
    //拍照end
}
